package cn.demo.um.support.handler.base;

import cn.demo.um.domain.UmAttrData;
import cn.demo.um.service.IUmAttrDataService;
import cn.demo.um.support.factory.ISearchAttrIndexFactory;
import cn.demo.um.support.handler.MatcherContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PluralBaseMatcherHandler implements IBaseMatcherHandler {

    @Autowired
    private IUmAttrDataService umAttrDataService;

    @Override
    public void handler(MatcherContext matcherContext, String attrCode, double score) {
        ISearchAttrIndexFactory searchAttrIndexFactory = matcherContext.getSearchAttrIndexFactory();
        Set<String> userId = new HashSet<>();
        /*这里拿到的和下面村的是同一个*/
        Map<String, List<String>> indexMap = (Map<String, List<String>>) searchAttrIndexFactory.getIndexStructure(attrCode, matcherContext.getSex());
        // 获取匹配因子
        List<String> factors = matcherContext.getFactor(attrCode);
        factors.forEach(factor -> {
            List<String> userIds = indexMap.get(factor);
            if (userIds != null) {
                userId.addAll(userIds);
            }
        });
        matcherContext.addMatchScopeAttr(userId, score, attrCode);
    }

    @Override
    public Map<String, List<String>> buildInvertedIndex(List<UmAttrData> umAttrDataList, String attrCode) {
        Map<String, List<String>> invertedIndex = umAttrDataList.stream()
                .collect(Collectors.groupingBy(UmAttrData::getAttrValue, Collectors.mapping(UmAttrData::getUserId, Collectors.toList())));
        return invertedIndex;
    }
}
